; sidglue.asm
; Ties the parts together

	.include "vicrom.inc"
	.macpack longbranch

	.export boot
	.export ptr

	.import entry
	
	.import __ZEROPAGE_LOAD__
	.import __ZEROPAGE_RUN__
	.import __STACK_LOAD__
	.import __STACK_RUN__
	.import __THIRD_LOAD__
	.import __THIRD_RUN__

	VIC_BASE = $9000
	VIA1_BASE = $9110
	VIA2_BASE = $9120

	IRQ_VECTOR = $0314
	NMI_VECTOR = $0318
	IRQ_TAIL = $EB15

	.segment "ZEROPAGE"

src:		.res 2
tgt:		.res 2
cnt:		.res 2
ptr:		.res 2

	.segment "RODATA"

splash_name:	.byte "sidsplash.prg"
	splash_len = * - splash_name
	
song_adr:		.incbin "cybernoid2.prg"
	song_start = song_adr+2
	song_length = * - song_start
	
	.segment "CODE"
	
;----------------------------------------------------------------------------
play:		; disable NMI
			lda #$7F				; disable all interrupts
			sta VIA1_BASE+14
			
			; Clear autostart area
			lda #0
			ldx #0
@clra0:		sta $A000, x
			inx
			bne @clra0
			
			; copy song
			lda #<song_start
			sta src
			lda #>song_start
			sta src+1
			lda song_adr
			sta tgt
			lda song_adr+1			
			sta tgt+1
			lda #<song_length
			sta cnt
			lda #>song_length
			sta cnt+1
			
			ldy #0
@cploop:	lda (src), y
			sta (tgt), y
			inc src
			bne @srcdone
			inc src+1
@srcdone:	inc tgt
			bne @tgtdone
			inc tgt+1
@tgtdone:	ldx cnt
			bne @nohi
			ldx cnt+1
			beq @donecp
			dec cnt+1
@nohi:		dec cnt
			jmp @cploop
@donecp:
			; copy zeropage & 
			sei
			ldx #0
@zploop:	lda __ZEROPAGE_LOAD__, x
			sta __ZEROPAGE_RUN__, x
			lda __STACK_LOAD__, x
			sta __STACK_RUN__, x
			lda __THIRD_LOAD__, x
			sta __THIRD_RUN__, x
			inx
			bne @zploop
			
			; start SID Emu
			jmp entry

;----------------------------------------------------------------------------
boot:		; load & run splash		
			lda #$01
			sta ptr
			lda #$12
			sta ptr+1
			lda #splash_len
			ldx #<splash_name
			ldy #>splash_name
			jsr SETNAM
			lda #1			; LFN
			ldx $BA			; device
			ldy #0			; secondary address
			jsr SETLFS
			jsr OPEN
			ldx #1			; set #1 for input
			jsr CHKIN
			jcs load_fail
			; ignore address
			jsr BASIN
			jsr BASIN
@read_loop:	ldy $90			; check status
			bne @eof
			jsr BASIN
			jcs load_fail
			ldy #0
			sta (ptr), y
			inc ptr
			bne @read_loop
			inc ptr+1
			bne @read_loop
@eof:		jsr CLRCH
			lda #1
			jsr CLOSE
			; set-up play address 
			lda #<play
			sta $032A
			lda #>play
			sta $032B
			; run splash
			ldx ptr
			ldy ptr+1
			stx $2D		; save end address
			sty $2E
			jsr $C659	; CLR
			jsr $C533	; Relinks BASIC Program from and to any address...
			jmp $C7AE	; BASIC Warm Start (RUN)
			
load_fail:	lda #1
			jsr CLOSE
			pla
			pla
			lda #<fail_msg
			ldy #>fail_msg
			jmp STROUT

fail_msg:	.byte "?load error", 0
